const mysql = require('mysql2/promise');
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'bookshop'
};

/**
 * 评论控制器
 */
exports.getBookComments = async (req, res) => {
  try {
    const { bookId } = req.params;
    const connection = await mysql.createConnection(dbConfig);
    
    const [rows] = await connection.execute(`
      SELECT c.*, u.username, u.avatar 
      FROM comments c
      LEFT JOIN users u ON c.user_id = u.id
      WHERE c.book_id = ?
      ORDER BY c.created_at DESC
    `, [bookId]);
    
    await connection.end();
    
    res.json({
      code: 200,
      message: '获取评论成功',
      data: rows
    });
  } catch (error) {
    console.error('获取评论错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      data: null
    });
  }
};

exports.addComment = async (req, res) => {
  try {
    const { bookId } = req.params;
    const { content, rating } = req.body;
    const userId = req.user.id; // 从token中获取
    
    const connection = await mysql.createConnection(dbConfig);
    
    const [result] = await connection.execute(`
      INSERT INTO comments (user_id, book_id, content, rating, created_at)
      VALUES (?, ?, ?, ?, NOW())
    `, [userId, bookId, content, rating]);
    
    await connection.end();
    
    if (result.affectedRows > 0) {
      res.json({
        code: 200,
        message: '评论成功',
        data: {
          id: result.insertId,
          user_id: userId,
          book_id: bookId,
          content,
          rating,
          created_at: new Date()
        }
      });
    } else {
      res.status(400).json({
        code: 400,
        message: '评论失败',
        data: null
      });
    }
  } catch (error) {
    console.error('添加评论错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      data: null
    });
  }
};

exports.deleteComment = async (req, res) => {
  try {
    const { commentId } = req.params;
    const userId = req.user.id; // 从token中获取
    
    const connection = await mysql.createConnection(dbConfig);
    
    // 验证评论是否属于当前用户
    const [comments] = await connection.execute(`
      SELECT * FROM comments WHERE id = ? AND user_id = ?
    `, [commentId, userId]);
    
    if (comments.length === 0) {
      await connection.end();
      return res.status(403).json({
        code: 403,
        message: '没有权限删除此评论',
        data: null
      });
    }
    
    const [result] = await connection.execute(`
      DELETE FROM comments WHERE id = ?
    `, [commentId]);
    
    await connection.end();
    
    if (result.affectedRows > 0) {
      res.json({
        code: 200,
        message: '删除评论成功',
        data: null
      });
    } else {
      res.status(400).json({
        code: 400,
        message: '删除评论失败',
        data: null
      });
    }
  } catch (error) {
    console.error('删除评论错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      data: null
    });
  }
}; 